package com.geoserver.utils;

import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * FileName: ImageCompress
 * Create by fengzheng on 2019/4/26 10:47
 * Description: 图片压缩
 */

@Component
public class ImageCompress {

    private Image image;

    public BufferedImage resizeFix(Image mImage){

        this.image = mImage;

        int width = mImage.getWidth(null);
        int height = mImage.getHeight(null);

        int fWidth = 150;
        int fHeight = 93;

        // 以宽度为基准压缩
        if(width/height > fWidth/fHeight){
            int h = (height * fWidth / width);

            return resize(fWidth,h);
        }
        // 以高度为基准压缩
        else{
            int w = (width * fHeight / height);

            return resize(w,fWidth);
        }
    }

    /**
     * 压缩
     */
    private BufferedImage resize(int w,int h){
        BufferedImage bufferedImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
        bufferedImage.getGraphics().drawImage(image,0,0,w,h,null);

        return bufferedImage;
    }
}
